package tgc.edu.tgq.demo.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import tgc.edu.tgq.demo.service.SysUserService;

/*配置文件*/
@Configuration
//让Secured设置登录权限生效
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
	@Autowired
	private SysUserService sysUserService;
	
//	配置方法1
	@Override
	//configure凭证管理 （auth凭证，自动生成）
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		//用户合法凭证
		auth.userDetailsService(sysUserService).passwordEncoder(new BCryptPasswordEncoder());
		//设置后门，超级管理员 （{noop}加密的一种方式）
		auth.inMemoryAuthentication().withUser("aaa").password("{noop}1234").roles("DIY","ADMIN");
	}

//	配置方法2
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		//安全器令牌
		http.csrf().disable();
		http.headers().frameOptions().disable();    //解决iframe与安全器兼容性问题
		http.formLogin()
			//登录请求
			.loginPage("/login")
			.permitAll()
			.usernameParameter("username")
			.passwordParameter("pwd")
 			//设置登录成功跳转页面（CourseController中获取main跳转index ）
			.successForwardUrl("/main")
			//登录失败跳转页面
			.failureUrl("/login?error");
		http.logout().logoutUrl("/logout").permitAll();
		http.authorizeRequests().antMatchers("/static/**","/webjars/**").permitAll();//文件下所有静态资源都可以访问
		http.authorizeRequests().anyRequest().authenticated();    //除此之外的都必须通过请求验证才能访问
		
	}


}
